package org.groupg.practice;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class AdvancedOkHttpConfig {

    public static void main(String[] args) {
        // 1. 配置缓存目录和大小
        File cacheDirectory = new File("/path/to/cache/dir");
        int cacheSize = 10 * 1024 * 1024; // 10 MB
        Cache cache = new Cache(cacheDirectory, cacheSize);

        // 2. 创建带有自定义配置的 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS) // 连接超时
            .readTimeout(30, TimeUnit.SECONDS)    // 读取超时
            .writeTimeout(30, TimeUnit.SECONDS)   // 写入超时
            .cache(cache)                         // 设置缓存
            .addInterceptor(new Interceptor() {   // 添加拦截器
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    // 添加统一的认证头
                    Request newRequest = originalRequest.newBuilder()
                        .header("Authorization", "Bearer your_static_token_here")
                        .build();
                    return chain.proceed(newRequest);
                }
            })
            .build();

        // 使用配置好的 client 发送请求...
        Request request = new Request.Builder()
            .url("https://api.example.com/some/data")
            .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("Advanced config request success: " + response.body().string());
            } else {
                System.out.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
